package xddq

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"runtime/debug"
	"time"
	D "websocket_apn/define"
	"websocket_apn/log"
	"websocket_apn/proto"

	"github.com/gorilla/websocket"
)

const (
	Task_Type_FuDi_Self = 0
	Task_Type_FuDi_User = 1
	FuDiUserData        = "fudi.json"
)

/*
广告刷新自己的福地
[DEBUG] [2024/04/29 00:17:16] [PRJ/websocket_apn/main_test.go]:[  196]:   S_HOMELAND_REFRESH_RESOURCE - id:3109673861602
[DEBUG] [2024/04/29 00:17:16] [PRJ/websocket_apn/main_test.go]:[  197]:   PayloadBytes: 71 AB 00 00 00 23 00 00 52 3F 00 00 02 D4 07 01 81 E2 08 01 10 FF FF FF FF FF FF FF FF FF 01 18 00 28 00
*/
func (xd *XdDriver) FuDiDataInit() {
	xd.UserData.FuDiData.Config[D.R_Resource_XianYu] = 99
	xd.UserData.FuDiData.Config[D.R_Resource_Stone] = 99
	xd.UserData.FuDiData.Config[D.R_Resource_Peech] = 4
	xd.UserData.FuDiData.Config[D.R_Resource_JingPingShui] = 4
	xd.UserData.FuDiData.Config[D.R_Resource_LiuLiZhu] = 99
	xd.UserData.FuDiData.Config[D.R_Resource_TianYanLin] = 5
	xd.UserData.FuDiData.Config[D.R_Resource_KunLunTie] = 99
	xd.UserData.FuDiData.TakeFuDiChan = make(chan D.UserResourceInfo, 20)
	xd.UserData.FuDiData.MsgChan = make(chan D.Message, 50)
	xd.UserData.FuDiData.UserIdMap = make(map[string]D.UserResourceInfo, 20)
	xd.InitFuDiUserFromFile()

}

// 需要采摘的资源对应的 用户ID及序号
func (xd *XdDriver) CheckTakeInfo(checkType int) (D.UserResourceInfo, int) {
	maxData := -1
	dataLevel := 0
	if checkType == Task_Type_FuDi_Self && !xd.UserData.FuDiData.UserInfo.IsTake {
		for idx, data := range xd.UserData.FuDiData.UserInfo.ResourceInfo {
			if data.Type != D.R_Resource_Unkown {
				if data.Level >= xd.UserData.FuDiData.Config[data.Type] {
					if data.Level > dataLevel {
						maxData = idx
						dataLevel = data.Level
					}
				}
			}
		}
		if maxData > 0 {
			return xd.UserData.FuDiData.UserInfo, maxData
		}
	} else if checkType == Task_Type_FuDi_User {
		for _, allData := range xd.UserData.FuDiData.UserIdMap {
			if !allData.IsTake {
				maxData = -1
				dataLevel = 0
				for idx, data := range allData.ResourceInfo {
					if data.Type != D.R_Resource_Unkown {
						if data.Level >= xd.UserData.FuDiData.Config[data.Type] {
							if data.Level > dataLevel {
								maxData = idx
								dataLevel = data.Level
							}
						}
					}
				}
				if maxData > 0 {
					return allData, maxData
				}
			}
		}
	}
	return D.UserResourceInfo{}, -1
}

// 是否需要采集资源
func (xd *XdDriver) CheckNeedTake(info *D.UserResourceInfo) bool {
	info.TakeIdx = -1
	dataLevel := -1
	if info.UserId != xd.UserData.UserID && info.IsTake {
		return false
	}
	for idx, data := range info.ResourceInfo {
		if data.Type != D.R_Resource_Unkown {
			if !data.IsTake && data.Level >= xd.UserData.FuDiData.Config[data.Type] {
				if data.Level > dataLevel {
					info.TakeIdx = idx
					dataLevel = data.Level
				}
			}
		}
	}
	if info.TakeIdx >= 0 {
		userName := info.UserId
		if _, ok := xd.UserData.FuDiData.UserIdMap[info.UserId]; ok {
			userName = xd.UserData.FuDiData.UserIdMap[info.UserId].Name
		}
		log.Warnf("准备采摘[%s]的福地第%d个资源: %+v", userName, info.TakeIdx+1, info.ToString())
		return true
	}
	return false
}
func (xd *XdDriver) FindUserResourceByUserId(userId string) {
	sendMsg := proto.Get_Cmd_Data(xd.userInfo.PlayerId, proto.S_HOMELAND_ENTER, "08"+userId)
	xd.UserData.FuDiData.MsgChan <- *sendMsg
}
func (xd *XdDriver) UpdateFuDiData(allInfo []D.UserResourceInfo) {
	xd.UserData.FuDiData.UserIdMap = make(map[string]D.UserResourceInfo, 20)
	for _, info := range allInfo {
		if !info.IsTake {
			xd.FindUserResourceByUserId(info.UserId)
		}
		if _, ok := xd.UserData.FuDiData.UserIdMap[info.UserId]; ok {
			userInfo := xd.UserData.FuDiData.UserIdMap[info.UserId]
			userInfo.IsTake = info.IsTake
			userInfo.AllLevel = info.AllLevel
			userInfo.ResourceInfo = info.ResourceInfo
		} else {
			xd.UserData.FuDiData.UserIdMap[info.UserId] = info
		}
		if xd.CheckNeedTake(&info) {
			xd.UserData.FuDiData.TakeFuDiChan <- info
		}
	}
}

func (xd *XdDriver) CheckFuDiData(info D.UserResourceInfo, isSelf bool) {
	if isSelf {
		userName := info.UserId
		if info.UserId != xd.UserData.UserID {
			log.Warnf("成功开始采摘[%s]的福地资源: %+v", userName, info.ToString())
		} else {
			info.Name = "自己"
			needTake := xd.CheckNeedTake(&info)
			log.Infof("UserId %s,UserID %s,LeftMouseNum %d", info.UserId, xd.UserData.UserID, xd.UserData.FuDiData.LeftMouseNum)
			//采集自己的并召回
			if info.UserId == xd.UserData.UserID && xd.UserData.FuDiData.LeftMouseNum > 0 {
				for idx, resource := range info.ResourceInfo {
					if idx == info.TakeIdx || resource.IsTake {
						continue
					}
					xd.Send(proto.Get_Cmd_Data(xd.userInfo.PlayerId, proto.S_HOMELAND_DISPATCH_WORKER, fmt.Sprintf("08 %s 10 %02X 18 01", info.UserId, idx)))
					time.Sleep(100 * time.Millisecond)
					xd.Send(proto.Get_Cmd_Data(xd.userInfo.PlayerId, proto.S_HOMELAND_DISPATCH_WORKER, fmt.Sprintf("08 %s 10 %02X 18 00", info.UserId, idx))) //召回
					time.Sleep(100 * time.Millisecond)
				}
			}
			if needTake {
				xd.UserData.FuDiData.TakeFuDiChan <- info
			}
		}
		if _, ok := xd.UserData.FuDiData.UserIdMap[info.UserId]; ok {
			userName = xd.UserData.FuDiData.UserIdMap[info.UserId].Name
		}
	} else if len(info.UserId) > 1 {
		if _, ok := xd.UserData.FuDiData.UserIdMap[info.UserId]; ok {
			userData := xd.UserData.FuDiData.UserIdMap[info.UserId]
			log.Warnf("探寻[%s]的福地: %+v", userData.Name, info.ToString())
			userData.IsTake = info.IsTake             //是否有人在采摘
			userData.ResourceInfo = info.ResourceInfo //资源信息
			xd.UserData.FuDiData.UserIdMap[info.UserId] = userData
			//log.Debugf("CheckFuDiData: %+v", xd.UserData.FuDiData.UserIdMap[info.UserId])
		} else {
			log.Warnf("探寻到[%s]的福地: %+v", info.UserId, info.ToString())
			xd.UserData.FuDiData.UserIdMap[info.UserId] = info
		}
		if xd.CheckNeedTake(&info) {
			xd.UserData.FuDiData.TakeFuDiChan <- info
		}
	}
}

func (xd *XdDriver) CheckFudiHomeManageInfoData(allInfo []D.FudiHomeManageInfo) {
	for _, info := range allInfo {
		log.Warnf("福地-撤销采集【%s】的第%d个 %d级 %s", info.UserId,
			info.ResourceInfo.Location+1, info.ResourceInfo.Level, D.GameResource[info.ResourceInfo.Type][0])
		xd.Send(proto.Get_Cmd_Data(xd.userInfo.PlayerId, proto.S_HOMELAND_DISPATCH_WORKER, fmt.Sprintf("08 %s 10 %02d 18 00", info.UserId, info.ResourceInfo.Location)))
		time.Sleep(3 * time.Second)
		xd.FindUserResourceByUserId(info.UserId)
		time.Sleep(3 * time.Second)
	}
}

// 福地偷桃任务
func (xd *XdDriver) CheckNumberOfMiceInfoData(info D.FuDiData) {
	if info.MouseTotal > 0 || info.LeftMouseNum > 0 {
		xd.UserData.FuDiData.MouseTotal = info.MouseTotal
		xd.UserData.FuDiData.LeftMouseNum = info.LeftMouseNum
	}
}

// 用户资源信息
type SaveUserResourceInfo struct {
	UserId string //用户ID
	Name   string //用户姓名
}

func (xd *XdDriver) InitFuDiUserFromFile() error {
	return nil
	// 读取文件内容
	fileContent, err := ioutil.ReadFile(FuDiUserData)
	if err != nil {
		return err
	}
	// 解析文件内容为结构体数组
	var users []SaveUserResourceInfo
	err = json.Unmarshal(fileContent, &users)
	if err != nil {
		return err
	}
	for _, saveData := range users {
		UserResourceInfo := D.UserResourceInfo{
			UserId: saveData.UserId,
			Name:   saveData.Name,
			IsTake: false,
		}
		xd.UserData.FuDiData.UserIdMap[saveData.UserId] = UserResourceInfo
	}
	return nil
}
func (xd *XdDriver) SaveFuDiUserToFile() error {
	return nil
	var saveUsers []SaveUserResourceInfo
	for _, UserResourceInfo := range xd.UserData.FuDiData.UserIdMap {
		users := SaveUserResourceInfo{
			UserId: UserResourceInfo.UserId,
			Name:   UserResourceInfo.Name,
		}
		saveUsers = append(saveUsers, users)
	}
	// 将结构体数组转换为JSON格式
	jsonData, err := json.MarshalIndent(saveUsers, "", "    ")
	if err != nil {
		return err
	}

	// 将JSON数据写入文件
	err = ioutil.WriteFile(FuDiUserData, jsonData, 0644)
	if err != nil {
		return err
	}
	return nil
}

// 福地偷桃任务
func (xd *XdDriver) StartFuDiTask() {
	log.Debug("start Fu Di thread.")
	defer func() {
		if err := recover(); err != nil {
			log.Fatalf("process:\n%s", debug.Stack())
			time.Sleep(time.Second)
		}
	}()
	for {
		select {
		case <-xd.ctx.Done():
			{
				log.Warnf("StartFuDiTask process thread exit.")
				return
			}
		case info := <-xd.UserData.FuDiData.TakeFuDiChan:
			{
				log.Debugf("获取到资源信息:%+v", info)
				ResourceInfo := info
				idx := ResourceInfo.TakeIdx
				if ResourceInfo.IsTake && idx < 0 {
					break
				}
				msgData := &proto.MsgData{
					Cmd:      proto.S_HOMELAND_DISPATCH_WORKER,
					PlayerID: xd.userInfo.PlayerId,
				}
				var data []byte
				data, _ = proto.HexStrToBytes("08" + ResourceInfo.UserId + fmt.Sprintf("10%02d1801", idx))
				msgData.HexData = data
				msg := &D.Message{
					MessageType:  websocket.BinaryMessage,
					PayloadBytes: proto.EncodeMsgData(msgData),
				}
				userName := ResourceInfo.UserId
				if _, ok := xd.UserData.FuDiData.UserIdMap[ResourceInfo.UserId]; ok {
					userName = xd.UserData.FuDiData.UserIdMap[ResourceInfo.UserId].Name
				}
				log.Warnf("采摘[%s]的福地第%d个【%s %d级】", userName, idx+1, D.GameResource[ResourceInfo.ResourceInfo[idx].Type][0], ResourceInfo.ResourceInfo[idx].Level)
				xd.Send(msg)
				break
			}
		case sendMsg := <-xd.UserData.FuDiData.MsgChan:
			{
				xd.Send(&sendMsg)
				time.Sleep(2 * time.Second)
			}
		}
	}
}
